
(function($){
	$.fileObj = null;	//File对象
	
	var allowType = ["bmp","jpg","jpeg","png","gif","BMP","JPG","JPEG","PNG","GIF"];	//允许上传的图片类型
	
	var options = {};
	
	//上传图片
	$.uploadCutImg = function(){
		
		var returnData = null;
		
		var pos = $.jcropFun.getSelectPos();
		var josnString = "{'h':'"+pos.h+"','w':'"+pos.w+"','x':'"+pos.x+"','y':'"+pos.y+"','x2':'"+pos.x2+"','y2':'"+pos.y2+"'}";
		
		$.ajaxFileUpload({
            url: options.uploadAction, 
            async : false,		//同步
            type: 'post',
            data : {"poses":josnString},
//            contentType : "multipart/form-data",
            secureuri: false, //一般设置为false
            fileElementId: $.fileObj.attr("name"), // 上传文件的id、name属性名
            dataType: 'json', //返回值类型，一般设置为json、application/json
            elementIds: josnString, //传递参数到服务器
            success: function(data, status){  
            	
            	//调用回调函数
            	if(options.callFun!=null && typeof options.callFun=="string" ){
        			var callFun = options.callFun;
        			if(callFun.lastIndexOf("(")>=0){
        				callFun = callFun.substring(0,callFun.lastIndexOf("("));
        			}
        			window[callFun](data);	//将String转function，并传参运行
        		}else if(options.callFun!=null && typeof options.callFun=="function"){
        			options.callFun.call($.uploadCutImg,data); //调用回调函数，并传参运行
        		}
            	
            	returnData = data;
            },
            error: function(data, status, e){ 
                alert(e);
            }
        });
		
		$.fileObj.remove();
		var bodyIMGModal = $("body").find("div[id='myIMGModal_Plugin']");
		bodyIMGModal.modal("hide");
		$.fileObj = null;
		
		return;
	};
	
	var buildIMGModal = function(src){
		
	var html =  "<div aria-hidden='true' aria-labelledby='myModalLabel' role='dialog' tabindex='-1' id='myIMGModal_Plugin' class='modal fade'>"
				+ "<div class='modal-dialog'>"
				+ "<div class='modal-content' style='width:650px;height:600px;'>"
				+ "<div class='modal-header'>"
				+ "<button aria-hidden='true' data-dismiss='modal' class='close' type='button'>×</button>"
				+ "<h4 class='modal-title'>截图上传</h4>"
				+ "</div>"
				+ "<div class='modal-body'>"

				+ "<form class='form-horizontal' role='form' enctype='multipart/form-data'>"
				+ "<div class='form-group' style='width:100%;height:460px;'>"
					+ "<div class='col-lg-12' style='text-align:center'>"
					+ "<img src='"+src+"'  id='myIMG_plugin'/>" //style='width:600;height:550;'
					+ "</div>"
				+ "</div>"

				+ "<div class='form-group'>"
					+ "<div class='col-lg-offset-10 col-lg-2'>"
						+ "<button type='button' class='btn btn-info' onclick='$.uploadCutImg()'>确定</button>"
					+ "</div>" 
				+ "</div>" 
				
				+ "<input type='hidden' name='imgPoses'/>"
			
				+ "</form>"

				+ "</div>" + "</div>" + "</div>" + "</div>";
		        
		        return html;
        
	};
	
	$.jcropFun = {
		
		jcropAPI : null,
		initJcrop : function(){
			
			if (!$.Jcrop) {
	            return;
	        }
			
			
			if($.jcropFun.jcropAPI!=null) {
				$.jcropFun.jcropAPI.destroy();
			}
			
			var imgDom = arguments[0];
			var imgW = imgDom[0].width;
			var imgH = imgDom[0].height;
			if(imgW>600){
				imgW = 600;
			}
			
			if(imgH>450){
				imgH = 450;
			}else{
				imgH = "auto";
			}
			
			var options = { 
					allowSelect:false, //允许新选框
					allowMove  :true , //允许选框移动 
					aspectRatio: 1,    //选中区域宽高比为1，即选中区域为正方形 
					bgColor:"#ccc",    //裁剪时背景颜色设为灰色 
					bgOpacity:0.3,     //透明度设为0.1 
					allowResize:false, //不允许改变选中区域的大小 
					setSelect:[0,0,300,300], //初始化选中区域 
					bgFade   :true ,        //使用背景过渡效果
					keySupport : true ,
//					minSelect:[300,300],	 //选框最小选择尺寸。说明：若选框小于该尺寸，则自动取消选择
//					maxSize : [500,500] ,    //选框最大尺寸
//					minSize : [300,300] ,    //选框最校尺寸
					boxWidth:imgW,        //画布宽度
					boxHeight:imgH        //画布高度
				 };
			
			$(imgDom).Jcrop(options,function(){
				$.jcropFun.jcropAPI = this;
			}); 
			
		},
		//获取选框的值（实际尺寸）。得到选框几个点的坐标
		getSelectPos:function(){
			if($.jcropFun.jcropAPI == null){
				alert("Please init Jcrop!");
				return;
			}
			return $.jcropFun.jcropAPI.tellSelect();
		}
	};
	
	//截图
	$.fn.IMGCuter = function(){
		
		var userOptions = arguments[0];
		
		var defaultOptions = {
			uploadAction:"/upload/img/upload.json"
		};
		
		//合并默认options和用户的options
		var mergeOptions = $.extend({},defaultOptions,userOptions);
		options = mergeOptions;
		
		$.fileObj = $(this);
		var file = $(this)[0].files[0]; 
		
		//在body中寻找图片弹出层
		var bodyIMGModal = $("body").find("div[id='myIMGModal_Plugin']");
		
		if(typeof FileReader == "undefined"){
			alert("您的浏览器不支持FileReader");
		}else{
			var reader = new FileReader();     
			reader.readAsDataURL(file);     
			reader.onload = function(e){         
				
				if(bodyIMGModal == null || bodyIMGModal.length<1 ){
					var modalDiv = buildIMGModal(this.result);
					$("body").append(modalDiv);
					bodyIMGModal = $("body").find("div[id='myIMGModal_Plugin']");
				}else{
					var pluginImg = bodyIMGModal.find("img[id='myIMG_plugin']");
					pluginImg.attr("src",this.result);
				}
				
				//将file加入modal中，同时在原来file的位置加入一个新的file
				$.fileObj.parent().append($.fileObj.clone());
				bodyIMGModal.find("form").find("input[type='file']").remove();
				$.fileObj.attr("id",$.fileObj.attr("id")+"_");
				$.fileObj.attr("name",$.fileObj.attr("name")+"_");
				bodyIMGModal.find("form").append($.fileObj);	//将File加入modal中
				
				//验证图片格式是否正确
				if(!(file.type.indexOf('image')==0 && file.type && 
						$.inArray(file.name.substring(file.name.lastIndexOf(".")+1,file.name.length), allowType)>= 0 )){  
				    alert('您选择的文件格式不正确！');  
				    return ;  
				}  
				
				var imgDom = bodyIMGModal.find("img[id='myIMG_plugin']");
				var imgW = imgDom[0].width;
				var imgH = imgDom[0].height;
				 if(imgW<300){
					alert("所选图片宽度不能小于300像素！");
					return;
				}
				if(imgH<300){
					alert("所选图片高度不能小于300像素！");
					return;
				}
				
				$(bodyIMGModal).modal('show');
				//初始化Jcrop
				$.jcropFun.initJcrop(imgDom);
				
			};
		}
	};
})(jQuery);